import { System } from "@/FrontProcessing/System/System";
import { SelectedParts, SelectedEdgeInfo } from "@/FrontProcessing/interface";

/**
 * 获取当前选中的线
 */
export function get_selected_edge(sys: System) {
  const edge = { entity_id: -1, part_id: -1 };
  const currentSelectedEdges: Map<string, SelectedEdgeInfo> =
    sys.state.currentSelectedEdges;

  if (currentSelectedEdges.size < 2) {
    currentSelectedEdges.forEach((value) => {
      edge.entity_id = value.edgeId;
      edge.part_id = value.partId;
    });
  }

  return edge;
}

/**
 * 获取当前选中的点
 */
export function get_selected_node(sys: System) {
  return getSelectedEntity(sys, (selectedPart) => ({
    entity_id: selectedPart.vertexIds[0].vertexId,
    part_id: selectedPart.partId,
  }));
}

/**
 * 获取当前选中的面
 */
export function get_selected_face(sys: System) {
  return getSelectedEntity(sys, (selectedPart) => ({
    entity_id: selectedPart.faceIds[selectedPart.faceIds.length - 1],
    part_id: selectedPart.partId,
  }));
}

/**
 * 获取当前选中的体
 */
export function get_selected_body(sys: System) {
  return getSelectedEntity(sys, (selectedPart) => ({
    entity_id: selectedPart.partEntityId,
    part_id: selectedPart.partId,
  }));
}

/**
 * 获取当前选中的两个面
 * 暂时默认先选的是目标面，后选的是修剪工具面
 */
export function get_selected_2_faces(sys: System) {
  const selectedParts = sys.state.currentSelectedParts;
  const selectedPart1 = selectedParts[selectedParts.length - 1]; // 倒数第一个面
  const selectedPart2 = selectedParts[selectedParts.length - 2]; // 倒数第二个面

  return {
    target: {
      entity_id: selectedPart2.faceIds[selectedPart2.faceIds.length - 1],
      part_id: selectedPart2.partId,
    },
    trim: {
      entity_id: selectedPart1.faceIds[selectedPart1.faceIds.length - 1],
      part_id: selectedPart1.partId,
    },
  };
}

/**
 * 通用函数：获取当前选中的实体
 */
function getSelectedEntity(
  sys: System,
  mapper: (selectedPart: SelectedParts) => {
    entity_id: number;
    part_id: number;
  }
) {
  const selectedPart =
    sys.state.currentSelectedParts[sys.state.currentSelectedParts.length - 1];
  return mapper(selectedPart);
}
